#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

//默认权限
#define DFL_MODE 0666

myFILE *my_fopen(const char* path,const char *mode)
{
    int fd = 0;//文件描述符
    int flag = 0;//打开方式
    if(strcmp(mode,"r")==0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode,"w")==0)
    {
        flag |= (O_CREAT | O_TRUNC | O_WRONLY);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag |= (O_CREAT | O_APPEND | O_WRONLY);
    }
    else{}
    if(flag & O_CREAT)
    {
        //如果文件不存在,创建文件
        fd = open(path, flag, DFL_MODE);
        
    }
    else
    {
        fd = open(path, flag);
    }
    if(fd < 0) {
        errno = 2;
        return NULL;
    }
    myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
    if(!fp)
    {
        errno = 3;
        return NULL;
    }
    fp->end = 0;
    fp->flag = FLUSH_LINE;
    fp->fileno = fd;
    return fp;
}
int my_fwrite(const char* s,int num, myFILE *stream)
{
   memcpy(stream->buffer+stream->end, s, num);
   stream->end += num;
   //判断是否需要刷新
   if((stream->flag & FLUSH_LINE) && stream->end > 0 && stream->buffer[stream->end-1] == '\n')
   {
    //这里只模拟只有最后一个字符是'\n'的情况
    my_fflush(stream);
   }
   return num;
}

int my_fflush(myFILE* stream)
{
    //缓冲区还有数据
    if(stream->end > 0)
    {
        write(stream->fileno,stream->buffer, stream->end);
        stream->end = 0;
    }
    return 0;
}

int my_fclose(myFILE* stream)
{
    my_fflush(stream);
    return close(stream->fileno);
}
